

import 'dart:io';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

class NetworkUtils {

  ///网络是否链接
  static Future<bool> getNetWorkConnectBol() async {
    final connectivityResult = await (Connectivity().checkConnectivity());
    if (connectivityResult == ConnectivityResult.mobile) {
      // I am connected to a mobile network.
      return true;
    } else if (connectivityResult == ConnectivityResult.wifi) {
      // I am connected to a wifi network.
      return true;
    } else if (connectivityResult == ConnectivityResult.ethernet) {
      // I am connected to a ethernet network.
      return true;
    } else if (connectivityResult == ConnectivityResult.vpn) {
      // I am connected to a vpn network.
      // Note for iOS and macOS:
      // There is no separate network interface type for [vpn].
      // It returns [other] on any device (also simulator)
      return true;
    } else if (connectivityResult == ConnectivityResult.bluetooth) {
      // I am connected to a bluetooth.
    } else if (connectivityResult == ConnectivityResult.other) {
      // I am connected to a network which is not in the above mentioned networks.
    } else if (connectivityResult == ConnectivityResult.none) {
      // I am not connected to any network.
    }
    return false;
  }

  late var subscription;
  ///add:initState()
  addNetworkListener(){
    subscription = Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
      // Got a new connectivity status!
    });
  }

  ///add:dispose()
  removeNetworkListener(){
    subscription.cancel();
  }

  /// 检测网络可用(通过ping baidu连接)
  ///[showErrorConnect] 链接错误时候提示错误原因
  static Future<bool> checkInternet({bool showErrorConnect = false}) async {
    bool connectionStatus = false;
    try {
      String host = "www.baidu.com";
      final result = await InternetAddress.lookup(host);
      print("result-- $result");
      if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
        connectionStatus = true;
        print("connected $connectionStatus");
      }
    } on SocketException catch(e) {
      connectionStatus = false;
      if(showErrorConnect){
        EasyLoading.showToast('网络连接异常${kDebugMode?e.message:',请检查后重试'}',dismissOnTap: true,toastPosition: EasyLoadingToastPosition.bottom);
      }
    }
    return connectionStatus;
  }
}